import time
# 导入selenium
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

from redis_conn import get_rd_conn

# from selenium.webdriver.chrome.service import Service


# 设置 Chrome 选项
chrome_options = Options()
# chrome_options.add_argument("--headless")  # 启用无头模式（表示浏览器后台运行，不展示浏览器页面）
chrome_options.add_argument("--disable-gpu")  # 禁用 GPU 加速（某些系统需要）
chrome_options.add_argument("--no-sandbox")  # 禁用沙盒模式
chrome_options.add_argument("--disable-dev-shm-usage")  # 解决内存不足问题

# 获取redis连接
# rd = get_rd_conn()
# name = rd.get('name')
# print(f"获取键值对: name -> {name.decode('utf-8')}")
# print(f"获取键值对: name -> {name}")

# 打开chrome浏览器
browser = webdriver.Chrome(options=chrome_options)

# 打开指定的页面
browser.get("https://boce.aliyun.com/detect/dns?spm=a2c1d.8251892.domain-setting.ddetect.10115b76AbAlei&target=wap.chaokuaisw.cn&type=A")

# 等待指定元素出
element = WebDriverWait(browser, 10).until(
    EC.presence_of_element_located((By.CLASS_NAME, 'show-detection-data'))
)
# browser.implicitly_wait(5)
# 元素出现了，需要再等5秒，等数据页面渲染完成
time.sleep(10)

# 获取页面源码
# 只匹配解析结果那一列：//div[@type="textarea"]/span/span[@class="teamix-pro-ellipsis teamix-pro-ellipsis-single-line teamix-pro-field-output-tooltip"]
# html = browser.page_source
# htmlList = element.find_elements(By.XPATH, '//span[@class="teamix-pro-ellipsis teamix-pro-ellipsis-single-line teamix-pro-field-output-tooltip"]')
# 只匹配解析结果的那一列
htmlList = element.find_elements(By.XPATH, '//div[@type="textarea"]/span/span[@class="teamix-pro-ellipsis teamix-pro-ellipsis-single-line teamix-pro-field-output-tooltip"]')

resultList = []
for htmlEle in htmlList:
    str = htmlEle.text + ','
    print(str)
    if str not in set(resultList):
        resultList.append(str)
# 写入文件
file = open('./runtime/aliyun_dns_check.html', 'w', encoding='utf-8')
file.write(','.join(resultList))
file.close()


# 设置五秒后执行下一步
time.sleep(5)
# 关闭浏览器
browser.quit()